package net.thxjj.mobileServer.websocket;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;


public class AppSocketMap {
	private static Logger log = Logger.getLogger(String.valueOf(AppSocketMap.class));
	//保存连接的Socket连接
	public static  Map<String,Channel > connections = new HashMap<String,Channel>();
	
	
	//获取所有的设备JWT
	public static Set<String> getOnlineUser(){
		return connections.keySet();
	}


	/**
	 * 判断一个通道是否有用户在使用
	 * 可做信息转发时判断该通道是否合法
	 * @param channel
	 * @return
	 */
	public static boolean hasUser(Channel channel) {
		AttributeKey<String> key = AttributeKey.valueOf("user");
		return (channel.hasAttr(key) || channel.attr(key).get() != null);//netty移除了这个map的remove方法,这里的判断谨慎一点
	}


	/**
	 * 上线一个用户
	 *
	 * @param channel
	 * @param access_token
	 */
	public static void addUser(Channel channel, String access_token) {
		//先判断用户是否在web系统中登录?
		//这部分代码个人实现,参考上面redis中的验证

		connections.put(access_token, channel);
		AttributeKey<String> key = AttributeKey.valueOf("user");
		channel.attr(key).set(access_token);

	}



	/**
	 * 根据access_token获取用户的通道
	 *
	 * @param access_token
	 * @return
	 */
	public static Channel getChannelByToken(String access_token) {
		return connections.get(access_token);
	}

	/**
	 * 判断一个用户是否在线
	 *
	 * @param access_token
	 * @return
	 */
	public static Boolean online(String access_token) {
		return connections.containsKey(access_token) && connections.get(access_token) != null;
	}
	
	public static void removeSocketUser(Channel st){
		//移除连接
		AttributeKey<String> key = AttributeKey.valueOf("user");
		String access_token = st.attr(key).get();
		connections.remove(access_token);
	}
	
	
	
}
